import tick from './Loop/Tick';
import Stage from './UI/Stage';
import BaseManager from './Manager/Index';
class VCanvas {
  el: Element;
  options: any;
  canvas: HTMLCanvasElement;
  ctx: CanvasRenderingContext2D;
  stage: Array<Stage>;
  tick: () => void;

  constructor(el: Element | string, options?: any) {
    if (!el) {
      throw new Error('el must be exist!');
    }
    this.el = typeof el === 'string' ? this.query(el) : el;
    this.canvas = document.createElement('canvas');
    this.options = options;
    this.canvas.width = options?.width || 500;
    this.canvas.height = options?.height || 500;
    this.ctx = this.canvas.getContext('2d');
    const stage = new Stage(this);
    this.stage = [stage];

    this.el.appendChild(this.canvas);

    this.tick = tick(this.update.bind(this));
    this.render();
    this.start();
  }

  async start() {
    BaseManager.Start();
    this.tick();
  }

  update() {
    BaseManager.Update();
    this.tick();
  }

  query(el: string) {
    return document.querySelector(el);
  }
  render() {
    this.stage.forEach((stage) => {
      this.ctx.drawImage(stage.canvas, 0, 0, 500, 500);
    });
  }
}

export default VCanvas;
